//
//  IrisLefuManager.swift
//  Runner
//
//  Created by Mr.Zhang on 2025/3/5.
//

import Foundation
import PPBluetoothKit
import PPCalculateKit

typealias ScalSearchDeviceCallBack = (_ scaleDevice: [String:Any]?) -> Void
typealias ScalBluetoothStateCallBack = (_ bluetoothState:Int) -> Void

class LfManager:NSObject,PPBluetoothConnectDelegate,PPBluetoothServiceDelegate,PPBluetoothScaleDataDelegate {
    
    // 蓝牙状态
    var bluetoothState:Int = 0
    // 连接状态
    var connectState:Int = 0
    var XM_Apple : PPBluetoothPeripheralApple? //四电极
    var XM_Torre: PPBluetoothPeripheralTorre?  //八电极
    var XM_FoundDeviceArray  =  [(PPBluetoothAdvDeviceModel,CBPeripheral)]()
    
    /*
     PPBluetoothConnectManager是设备扫描和连接的核心类，主要实现以下功能：
     - 蓝牙状态监听
     - 扫描周边所支持的蓝牙设备
     - 连接指定的蓝牙设备
     - 断开指定设备的连接
     - 停止扫描
     */
    
    let scaleManager:PPBluetoothConnectManager = PPBluetoothConnectManager()
    
    override init() {
        super.init()
    }
    
    // 搜索设备
    func startService() {
        _setSearchDelegate()
    }
    
    func stopService(){
        stopSearchDevice()
        //        clearDelegate()
    }
    
    // 搜索设备
    func stopSearchDevice() {
        scaleManager.stopSearch()
    }
    
    // 搜索设备
    func startSearchDevice() {
        scaleManager.searchSurroundDevice()
    }
    
    func clearDelegate() {
        self.scaleManager.updateStateDelegate = nil
        self.scaleManager.surroundDeviceDelegate = nil
    }
}

extension LfManager:PPBluetoothUpdateStateDelegate,PPBluetoothSurroundDeviceDelegate{
    
    
    func _setSearchDelegate(){
        print("_setSearchDelegate")
        scaleManager.updateStateDelegate = self
        scaleManager.surroundDeviceDelegate = self
    }
    
    //蓝牙状态
    /**
     PPBluetoothStateUnknown 未知状态
     PPBluetoothStateResetting 复位
     PPBluetoothStateUnsupported 不支持
     PPBluetoothStateUnauthorized 权限未授权
     PPBluetoothStatePoweredOff 蓝牙已关闭
     PPBluetoothStatePoweredOn 蓝牙已打开
     */
    func centralManagerDidUpdate(_ state: PPBluetoothState) {
        var bleState = 0
        print("centralManagerDidUpdate")
        if (state == .poweredOn){
            //搜索周边支持设备
            print("蓝牙已打开")
            bleState = 1
            self.startSearchDevice()
        }
        // LefuProductPlugin.shared.eventSink?([LefuNativeEventType.bluetoothStateChange:bleState])
    }
    
    //搜索到所支持的设备
    func centralManagerDidFoundSurroundDevice(_ device: PPBluetoothAdvDeviceModel!,andPeripheral peripheral: CBPeripheral!) {
        switch device.peripheralType {
        case .peripheralApple:
            print("搜索到所支持的设备类型：PPDevicePeripheralType.peripheralApple");
        default:
            break;
        }
        
        print("搜索到所支持的设备---->" + device.deviceName + String(describing: device.peripheralType));
        print(device);
        print(peripheral);
        if !self.XM_FoundDeviceArray.contains(where: { model in
            
            model.1.name == peripheral.name
        }){
            self.XM_FoundDeviceArray.append((device,peripheral))
            
        }
        //抛出设备
        LfProductPlugin.shared.eventSink?(["find_new_device":device.ppAston_JSONObject()]);
        //        if(connectState == 0){
        //            connectState = 1
        //            print("开始连接")
        //            print(device.ppAston_JSONObject());
        //        }else{
        //            print("已连接设备，忽略发现")
        //        }
        
    }
    
    
    // 开始连接
    func startConnDevice(_ device: PPBluetoothAdvDeviceModel!) {
        guard let foundDevice = self.XM_FoundDeviceArray.first(where: { $0.0.deviceMac == device.deviceMac }) else {
            print("❌ 没有找到匹配的设备")
            return
        }
        let choose_device = foundDevice.0  // 设备模型
        let peripheral = foundDevice.1  // 蓝牙设备
        print("✅ 找到设备: \(choose_device.deviceName), MAC: \(choose_device.deviceMac)")
        
        print("startConnDevice from LfManger")
        // 连接设备，设备对应代理方法
        self.scaleManager.connectDelegate = self
        self.scaleManager.connect(peripheral, withDevice: choose_device)
        switch(choose_device.peripheralType){
            case .peripheralTorre:
                print("case peripheralTorre")
                // 创建 Torre 类型协议操作对象
                self.XM_Torre = PPBluetoothPeripheralTorre(peripheral: peripheral, andDevice: choose_device)
                self.XM_Torre?.serviceDelegate = self
                self.XM_Torre?.scaleDataDelegate = self
                break
            case .peripheralApple:
                print("case peripheralApple")
                self.XM_Apple = PPBluetoothPeripheralApple(peripheral: peripheral, andDevice: choose_device)
                self.XM_Apple?.serviceDelegate = self
                self.XM_Apple?.scaleDataDelegate = self
                break
            @unknown default:
                print("undefined")
                break
        }
    }
    
    // 连接成功
    func centralManagerDidConnect() {
        print("centralManagerDidConnect")
        // 发现FFF0服务 ， XM_Torre为上一步骤创建的协议对象
        self.XM_Torre?.discoverFFF0Service()
        self.XM_Apple?.discoverFFF0Service()
        
    }
    
    // 连接失败
    func centralManagerDidFail(toConnect error: Error!) {
    }
    
    // 设备断开连接
    func centralManagerDidDisconnect() {
    }
    
    // 发现服务成功（FFF0）
    func discoverFFF0ServiceSuccess() {
        print("discoverFFF0ServiceSuccess")
        // 更新MTU，更新成功后就可以使用 Ice 协议对象提供的功能了
        self.XM_Torre?.codeUpdateMTU({[weak self] statu in
            
            guard let `self` = self else {return}
            
            //            self.XM_IsConnect = true
            
        })
        
        // 开始测量 测量前调用
        self.XM_Torre?.codeStartMeasure({ status in
        })
        
    }
    
    // 测量中，接收测量过程数据，UI实时测量数据可以使用该方法接收的数据（不稳定重量、测量状态）
    func monitorProcessData(_ model: PPBluetoothScaleBaseModel!, advModel: PPBluetoothAdvDeviceModel!) {
        print("测量中: \(model.weight)")
        LfProductPlugin.shared.eventSink?(["unlock_weight":model.weight]);
    }
    
    // 测量完成，接收最终测量数据
    func monitorLockData(_ model: PPBluetoothScaleBaseModel!, advModel: PPBluetoothAdvDeviceModel!) {
        print("测量完成 \(model.weight)")
        var modelJSON = model.ppAston_JSONObject() as? [String: Any] ?? [:]
        let advModelJSON = advModel.ppAston_JSONObject()
        modelJSON["deviceModel"] = advModelJSON
        LfProductPlugin.shared.eventSink?(["lock_weight":model.weight,"bodyBaseModel": modelJSON]);
        self.stopService()
    }
    
    /// 适配状态
    /// - Parameter state: <#state description#>
    /// - Returns: <#description#>
    private func setupBlutetoothState(_ state: PPBluetoothState) -> Int {
        
        var bleState = BluetoothState.off
        
        if state == .unauthorized || state == .unknown ||
            state == .unsupported
        {
            
            bleState = BluetoothState.off
            
        } else if state == .poweredOff {
            
            bleState = BluetoothState.off
            
        } else if state == .poweredOn {
            
            bleState = BluetoothState.on
            
        }  else {
            
            bleState = BluetoothState.off
        }
        
        return bleState
    }
}
